package codeTopPractice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 三数之和 {

    public static void main(String[] args) {

    }
    //排序+双指针，while循环去重
    public static List<List<Integer>> threeSum(int[] nums){
        ArrayList<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        for (int k = 0; k <nums.length-2 ; k++) {
            if(nums[k]>0) break;
            if(k>0 && nums[k]==nums[k-1]) continue;
            int i = k+1,j = nums.length-1;
            while (i < j){
                int sum = nums[k]+nums[i]+nums[j];
                if(sum<0){
                    while (i<j && nums[i] == nums[++i]);
                }else if(sum>0){
                    while (i<j && nums[j] == nums[j--]);
                }else {
                    list.add(new ArrayList<Integer>(Arrays.asList(nums[k],nums[i],nums[j])));
                    while (i<j && nums[i]==nums[++i]);
                    while (i<j && nums[j]==nums[--j]);
                }
            }
        }

        return list;
    }

}
